import sys,os

kilobytes = 1024
megabytes = kilobytes*1024
chunksize = int(200*megabytes) # default chunksize

def split(fromfile,todir,chunksize=chunksize):
    # 检查保存路径是否存在
    if not os.path.exists(todir):  
        os.mkdir(todir)          
    else:
        for fname in os.listdir(todir):
            os.remove(os.path.join(todir,fname))
    partnum = 0
    # 读取源文件
    inputfile = open(fromfile,'rb')
    while True:
        chunk = inputfile.read(chunksize)
        # 空文件退出
        if not chunk:
            break
        partnum += 1
        filename = os.path.join(todir,('data%04d.txt'%partnum))
        fileobj = open(filename,'wb')
        fileobj.write(chunk)
        fileobj.close()
    return partnum

if __name__=='__main__':
        fromfile  = "D:/BaiduNetdiskDownload/data.txt"
        todir     = "./result"
        chunksize = int(128*megabytes)
        absfrom,absto = map(os.path.abspath,[fromfile,todir])
        print('Splitting',absfrom,'to',absto,'by',chunksize)
        try:
            parts = split(fromfile,todir,chunksize)
        except:
            print('Error during split:')
            print(sys.exc_info()[0],sys.exc_info()[1])
        else:
            print("共划分为{0}个子文件".format(parts))
            print("保存路径：",absto)